<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
<!--          <a-col :xl="6" :lg="7" :md="8" :sm="24">-->
<!--            <a-form-item label="仓库编号">-->
<!--              <a-input placeholder="请输入仓库编号" v-model="queryParam.warehouseCode"></a-input>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库">
              <j-dict-select-tag placeholder="请选择仓库" v-model="queryParam.warehouseCode" dictCode="erp_warehouse,name,code"/>
<!--              <a-input placeholder="请输入库位编号" v-model="queryParam.warehouseLocationCode"></a-input>-->
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="6" :md="6" :sm="6">
            <a-form-item label="入库起始日期">
              <a-date-picker type="ge" v-model="queryParam.inOutDate_begin" :format="dateFormat" :valueFormat="dateFormat" @change="changeDate"/>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="入库截止日期">
              <a-date-picker type="le" v-model="queryParam.inOutDate_end"  :format="dateFormat" :valueFormat="dateFormat" @change="changeDate"/>
            </a-form-item>
          </a-col>
<!--          <a-col :xl="6" :lg="7" :md="8" :sm="24">-->
<!--            <a-form-item label="操作类型">-->
<!--              <j-dict-select-tag placeholder="请选择操作类型" v-model="queryParam.operationCategory" dictCode="kc_operation_category"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :xl="10" :lg="11" :md="12" :sm="24">-->
<!--            <a-form-item label="开始日期">-->
<!--              <j-date placeholder="请选择开始日期" class="query-group-cust" v-model="queryParam.preparedTime_begin"></j-date>-->
<!--              <span class="query-group-split-cust"></span>-->
<!--              <j-date placeholder="请选择结束日期" class="query-group-cust" v-model="queryParam.preparedTime_end"></j-date>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a-button type="primary" @click="copyInfo" icon="copy" style="margin-left: 8px">复制</a-button>
              <a-button type="primary" @click="saveChange" icon="save" style="margin-left: 8px">保存</a-button>
              <a-button type="primary" icon="download" @click="handleExportXls('物料库位表')" style="margin-left: 8px">导出</a-button>
              <!--              <a @click="handleToggleSearch" style="margin-left: 8px">-->
              <!--                {{ toggleSearchStatus ? '收起' : '展开' }}-->
              <!--                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>-->
              <!--              </a>-->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
    </div>

    <!-- table区域-begin -->
    <div>
<!--      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
<!--        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项-->
<!--        <a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
<!--      </div>-->
      <a-card title="库存信息">
      <j-vxe-table
        keep-source
        ref="table"
        class="bold-border"
        :scroll="{x:true}"
        :columns="columns"
        :maxHeight="400"
        :dataSource="dataSource"
        :pagination="ipagination"
        :rowNumber="true"
        :rowSelection="true"
        :toolbar="false"
        :clickSelectRow="true"
        rowSelectionType="radio">
        <template v-slot:erpLocationName="props">
          <tsl-warehouse v-model="props.value" :disabled="formDisabled" :rowData='props' @handlerOk="warehouseOk"></tsl-warehouse>
        </template>
      </j-vxe-table>
      </a-card>
      <a-card title="复制信息">
        <j-vxe-table
          keep-source
          ref="table1"
          class="bold-border"
          :scroll="{x:true}"
          :columns="columns1"
          :maxHeight="200"
          :disabled="formDisabled"
          :dataSource="selectionDataSource"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="false"
          :autoResize="true">
          <template v-slot:erpLocationName="props">
            <tsl-warehouse v-model="props.value" :disabled="formDisabled" :rowData='props' @handlerOk="warehouseOk1"></tsl-warehouse>
          </template>
        </j-vxe-table>
      </a-card>
    </div>

<!--    <buss-inventory-details-modal ref="modalForm" @ok="modalFormOk"/>-->
    <buss-in-out-detail-list-modal ref="selectInOutDetailList"
                                   :modalWidth="modalWidth"
                                   :code="code"
                                   :quantity="quantity"
                                   :category="category">
    </buss-in-out-detail-list-modal>
  </a-card>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  // import BussInventoryDetailsModal from './modules/BussInventoryDetailsModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import '@/assets/less/TableExpand.less'
  import BussInOutDetailListModal from "@comp/base/modal/BussInOutDetailListModal";
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import TslWarehouse from '@comp/tsl/TslWarehouse.vue'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { validateDuplicateValue , randomNumber, randomUUID } from '@/utils/util'
  import { postAction } from '@api/manage'
  import moment from 'dayjs'


  export default {
    name: "BussInventoryDetailsList",
    mixins:[JeecgListMixin],
    components: {
      TslWarehouse,
      // BussInventoryDetailsModal,
      BussInOutDetailListModal,
    },
    data () {
      return {
        description: '库存明细管理页面',
        modalWidth: 1300,
        category: '',
        code: '',
        quantity: '',
        type: 'radio',
        warehouseId: '',
        inventoryId: '',
        selectionDataSource: [],
        dateFormat: 'YYYY-MM-DD',
        queryParam:{
          inOutDate_begin : moment().subtract(7, 'days').format('YYYY-MM-DD'),
          inOutDate_end : moment().format('YYYY-MM-DD')
        },
        // 表头
        columns: [
          {
            title:'单据编号',
            width:"150px",
            key: 'code'
          },
          {
            title:'物料种类',
            width:"120px",
            key: 'categoryCode_dictText'
          },
          {
            title:'物料编号',
            width:"120px",
            key: 'materialCode'
          },
          {
            title:'客户物料编号',
            width:"120px",
            dataIndex: 'customerMaterialCode'
          },
          {
            title:'物料名称',
            width:"200px",
            key: 'materialName'
          },
          {
            title:'规格型号',
            width:"120px",
            key: 'noneSpec'
          },
          {
            title:'单位',
            type: JVXETypes.select,
            width:"80px",
            dictCode: 'ji_unit',
            key: 'meUnit',
            disabled: true
          },
          {
            title:'库存数量',
            width:"100px",
            key: 'quantity'
          },
          // {
          //   title:'入库数量',
          //   width:"100px",
          //   key: 'inventoryQuantity'
          // },
          // {
          //   title:'出库数量',
          //   width:"100px",
          //   key: 'outboundQuantity'
          // },
          // {
          //   title:'占用数量',
          //   width:"100px",
          //   key: 'occupationQuantity'
          // },
          // {
          //   title:'仓库编号',
          //   width: '120px',
          //   key: 'warehouseCode'
          // },
          // {
          //   title:'仓库名称',
          //   width: '120px',
          //   key: 'warehouseName'
          // },
          // {
          //   title:'库位编号',
          //   key: 'warehouseLocationCode',
          //   type: JVXETypes.selectDictSearch,
          //   width: '150px',
          //   // 【字典表配置信息】：数据库表名,显示字段名,存储字段名
          //   dict: 'erp_location,name,id',
          //   placeholder: '请选择${title}',
          // },
          {
            title: '库位编号',
            key: 'warehouseLocationCode',
            width: '120px',
          },
          {
            title:'库位',
            key: 'warehouseLocationName',
            type: JVXETypes.slot,
            slotName: 'erpLocationName',
            width: '150px',
            validateRules: [{ required: true, message: '请选择${title}' }]
          },
          {
            title:'批次号',
            width:"100px",
            key: 'batch'
          },
          {
            title:'物料批号',
            width:"100px",
            key: 'materialBatchNumber'
          },
          {
            title:'入库日期',
            key: 'inOutDate',
            width:"120px",
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'生产日期',
            key: 'productionDate',
            width:"120px",
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'限用日期',
            key: 'restrictedDate',
            width:"120px",
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'状态',
            width:"80px",
            key: 'status_dictText'
          },
          {
            title:'质检状态',
            width:"80px",
            key: 'qualityInspectionStatus_dictText'
          },
          {
            title:'供应商编号',
            width:"120px",
            key: 'supplierCode'
          },
          {
            title:'供应商名称',
            width:"120px",
            key: 'supplierName'
          },
          {
            title:'宝洁供应商编码',
            key: 'bjSupplierCode',
            width:"120px",
          },
          {
            title:'宝洁供应商',
            key: 'bjSupplier',
            width:"120px",
          },
          {
            title:'宝洁单号',
            key: 'bjOder',
            width:"120px",
          },
          {
            title:'辅助单位',
            width:"80px",
            key: 'auUnit_dictText'
          },
          {
            title:'辅助数量',
            width:"80px",
            key: 'auxiliaryQuantity'
          },
          {
            title:'制单人',
            width:"120px",
            key: 'preparedBy'
          },
          {
            title:'制单日期',
            key: 'preparedTime',
            width:"120px",
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          }
        ],
        columns1: [
          {
            title:'单据编号',
            width:"150px",
            key: 'code'
          },
          {
            title:'物料种类',
            width:"120px",
            key: 'categoryCode_dictText'
          },
          {
            title:'物料编号',
            width:"120px",
            key: 'materialCode'
          },
          {
            title:'客户物料编号',
            width:"120px",
            dataIndex: 'customerMaterialCode'
          },
          {
            title:'物料名称',
            width:"200px",
            key: 'materialName'
          },
          {
            title:'规格型号',
            width:"120px",
            key: 'noneSpec'
          },
          {
            title:'单位',
            type: JVXETypes.select,
            width:"80px",
            dictCode: 'ji_unit',
            key: 'meUnit',
            disabled: true
          },
          {
            title:'库存数量',
            type: JVXETypes.inputNumber,
            width:"100px",
            key: 'quantity',
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          // {
          //   title:'入库数量',
          //   width:"100px",
          //   key: 'inventoryQuantity'
          // },
          // {
          //   title:'出库数量',
          //   width:"100px",
          //   key: 'outboundQuantity'
          // },
          {
            title:'占用数量',
            width:"100px",
            key: 'occupationQuantity'
          },
          {
            title:'仓库编号',
            width: '120px',
            key: 'warehouseCode'
          },
          {
            title:'仓库名称',
            width: '120px',
            key: 'warehouseName'
          },
          // {
          //   title:'库位编号',
          //   key: 'warehouseLocationCode',
          //   type: JVXETypes.selectDictSearch,
          //   width: '150px',
          //   // 【字典表配置信息】：数据库表名,显示字段名,存储字段名
          //   dict: 'erp_location,name,id',
          //   placeholder: '请选择${title}',
          // },
          {
            title: '库位编号',
            key: 'warehouseLocationCode',
            width: '120px',
          },
          {
            title:'库位',
            key: 'warehouseLocationName',
            type: JVXETypes.slot,
            slotName: 'erpLocationName',
            width: '160px',
            validateRules: [{ required: true, message: '请选择${title}' }]
          },
          {
            title:'批次号',
            width:"100px",
            key: 'batch'
          },
          {
            title:'物料批号',
            width:"100px",
            key: 'materialBatchNumber'
          },
          {
            title:'入库日期',
            key: 'inOutDate',
            width:"120px",
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'生产日期',
            key: 'productionDate',
            width:"120px",
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'限用日期',
            key: 'restrictedDate',
            width:"120px",
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'状态',
            width:"80px",
            key: 'status_dictText'
          },
          {
            title:'质检状态',
            width:"80px",
            key: 'qualityInspectionStatus_dictText'
          },
          {
            title:'供应商编号',
            width:"120px",
            key: 'supplierCode'
          },
          {
            title:'供应商名称',
            width:"120px",
            key: 'supplierName'
          },
          {
            title:'宝洁供应商编码',
            key: 'bjSupplierCode',
            width:"120px",
          },
          {
            title:'宝洁供应商',
            key: 'bjSupplier',
            width:"120px",
          },
          {
            title:'宝洁单号',
            key: 'bjOder',
            width:"120px",
          },
          {
            title:'辅助单位',
            width:"80px",
            key: 'auUnit_dictText'
          },
          {
            title:'辅助数量',
            width:"80px",
            key: 'auxiliaryQuantity'
          },
          {
            title:'制单人',
            width:"120px",
            key: 'preparedBy'
          },
          {
            title:'制单日期',
            key: 'preparedTime',
            width:"120px",
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          }
        ],
        url: {
          list: "/detail/bussInventoryDetails/warehouseList",
          exportXlsUrl: "/detail/bussInventoryDetails/exportWarehouseXls",
          copyInfoUrl : "/detail/bussInventoryDetails/add"
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      formDisabled(){
        return this.disabled
      },
    },
    methods: {
      changeDate() {
        this.$forceUpdate()
      },
      historyRow(row){
        this.category = row.id;
        this.code = row.code;
        this.quantity = String(row.quantity);
        this.$refs.selectInOutDetailList.add();
        this.$refs.selectInOutDetailList.title = "查看库存明细";
        this.$refs.selectInOutDetailList.disableSubmit = false;
      },
      initDictConfig(){
      },
      warehouseOk({result,row}){
        this.dataSource.forEach(item=>{
          if(item.id == row.id){
            item.warehouseLocation = result.id
            item.warehouseLocationName = result.name
            item.warehouseLocationCode = result.code
            item.warehouseName= result.warehouseName
            item.warehouseCode = result.warehouseCode
            this.warehouseId = result.id
            this.inventoryId = row.id;
          }
        })
      },
      warehouseOk1({result,row}) {
        this.selectionDataSource.forEach(item => {
          if (item.id == row.id) {
            item.warehouseLocationCode = result.code
            item.warehouseLocationName = result.name
            item.warehouseLocation = result.id
            item.warehouseName= result.warehouseName
            item.warehouseCode = result.warehouseCode
          }
        })
      },
      searchReset() {
        this.queryParam = {}
        this.searchQuery();
      },
      searchQuery() {
        this.dataSource = [];
        this.selectionDataSource = [];
        this.loadData(1);
        this.warehouseId = '';
        this.inventoryId = ''
      },
      saveChange(){
        let rows =  this.$refs.table.selectedRows;
        if(rows.length<=0){
          this.$message.warn('请选择库存信息！')
          return;
        }
        if (this.inventoryId === null || this.inventoryId ===''){
          this.$message.warn('没有改动不需要保存！')
          return;
        }
        if (this.inventoryId != rows[0].id){
          this.$message.warn('当前选择的库存信息不是刚刚修改的记录！')
          return;
        }
        if (rows[0].qualityInspectionStatus !== "1" || rows[0].status  !== "1"){
          this.$message.warn('只能对质检合格的正常库存进行操作！')
          return;
        }
        let params={};
        params.id = this.inventoryId;
        params.warehouseLocationCode = this.warehouseId;
        if (this.selectionDataSource.length >0){
          if(this.selectionDataSource.length === 1){
            this.$message.warn('复制信息的数量至少两条并且数量和只能等于选择的库存信息！')
            return;
          }
          var quantity = 0;
          try {
            //有复制信息，求数量和跟选中的比较
            this.selectionDataSource.forEach(item => {
              if (item.detailId !== rows[0].id) {
                throw new Error('当前选择的库存信息不是刚刚复制的记录！')
              }
              var num = parseFloat(item.quantity);
              if(num == 0){
                throw new Error('复制信息中存在数量是0的记录，请修改！')
              }
              quantity = quantity + num;
            })
            if (quantity !== rows[0].quantity) {
              this.$message.warn('复制的总数量与原数据的数量不同！')
              return;
            }
          } catch (e) {
            // 跳出循环
            this.$message.warn(e.message); // 打印错误信息，然后跳出循环
            return;
          }
          params.bussInventoryDetails = this.selectionDataSource;
        }
        console.log(params)
        postAction(this.url.copyInfoUrl, params).then((res) => {
          this.uploading = false
          if(res.success){
            this.$message.success(res.message)
            this.warehouseId = '';
            this.inventoryId = ''
            this.selectionDataSource = [];
            this.searchQuery();
          }else{
            this.$message.warning(res.message)
          }
        })

      },
      copyInfo(){
        let rows =  this.$refs.table.selectedRows;
        console.log(rows)
        if(rows.length<=0){
          this.$message.warn('请选择要复制的库存信息！')
          return;
        }
        let detail = rows[0];
        if(parseFloat(detail.occupationQuantity)>0){
          this.$message.warn('被扣货库存不可复制！')
          return;
        }
        console.log(detail)
        if (detail.qualityInspectionStatus !== "1" || detail.status  !== "1"){
          this.$message.warn('只能对质检合格的正常库存进行操作！')
          return;
        }
        this.inventoryId = detail.id;
        let obj = {}
        obj.id = randomUUID();
        obj.code = detail.code;
        obj.categoryCode_dictText = detail.categoryCode_dictText;
        obj.customerMaterialCode = detail.customerMaterialCode;
        obj.materialCode = detail.materialCode;
        obj.materialName = detail.materialName;
        obj.noneSpec = detail.noneSpec;
        obj.meUnit = detail.meUnit;
        obj.quantity = detail.quantity;
        obj.warehouseName= detail.warehouseName
        obj.warehouseCode = detail.warehouseCode
        obj.warehouseLocation = detail.warehouseLocation;
        obj.warehouseLocationCode = detail.warehouseLocationCode;
        obj.warehouseLocationName = detail.warehouseLocationName;
        obj.batch = detail.batch;
        obj.materialBatchNumber = detail.materialBatchNumber;
        obj.inOutDate = detail.inOutDate;
        obj.productionDate = detail.productionDate;
        obj.restrictedDate = detail.restrictedDate;
        obj.status_dictText = detail.status_dictText;
        obj.qualityInspectionStatus_dictText = detail.qualityInspectionStatus_dictText;;
        obj.supplierCode = detail.supplierCode;
        obj.supplierName = detail.supplierName;
        obj.bjSupplierCode = detail.bjSupplierCode;
        obj.bjSupplier = detail.bjSupplier;
        obj.bjOder = detail.bjOder;
        obj.auUnit_dictText = detail.auUnit_dictText;
        obj.auxiliaryQuantity = detail.auxiliaryQuantity;
        obj.preparedBy = detail.preparedBy;
        obj.preparedTime = detail.preparedTime;
        obj.detailId = detail.id;
        this.selectionDataSource.push(obj);
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'inventoryId',text:'库存ID',dictCode:''})
        fieldList.push({type:'date',value:'inOutDate',text:'出入库日期'})
        fieldList.push({type:'date',value:'enterDate',text:'进厂日期'})
        fieldList.push({type:'date',value:'restrictedDate',text:'限用日期'})
        fieldList.push({type:'date',value:'productionDate',text:'生产日期'})
        fieldList.push({type:'string',value:'workshop',text:'车间',dictCode:''})
        fieldList.push({type:'string',value:'warehouseCode',text:'仓库编号',dictCode:''})
        fieldList.push({type:'string',value:'warehouseName',text:'仓库名称',dictCode:''})
        fieldList.push({type:'string',value:'warehouseLocation',text:'库位',dictCode:''})
        fieldList.push({type:'string',value:'warehouseLocationCode',text:'库位编号',dictCode:''})
        fieldList.push({type:'string',value:'batch',text:'批次号',dictCode:''})
        fieldList.push({type:'string',value:'materialBatchNumber',text:'物料批号',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'inventoryQuantity',text:'入库数量',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'outboundQuantity',text:'出库数量',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'occupationQuantity',text:'占用数量',dictCode:''})
        fieldList.push({type:'string',value:'operationCategory',text:'操作类别',dictCode:''})
        fieldList.push({type:'string',value:'code',text:'单据编号',dictCode:''})
        fieldList.push({type:'string',value:'materialId',text:'物料ID',dictCode:''})
        fieldList.push({type:'string',value:'materialCode',text:'物料编号',dictCode:''})
        fieldList.push({type:'string',value:'materialName',text:'物料名称',dictCode:''})
        fieldList.push({type:'string',value:'noneSpec',text:'规格型号',dictCode:''})
        fieldList.push({type:'string',value:'meUnit',text:'单位',dictCode:'ji_unit'})
        fieldList.push({type:'BigDecimal',value:'quantity',text:'库存数量',dictCode:''})
        fieldList.push({type:'string',value:'auUnit',text:'辅助单位',dictCode:'zl_unit'})
        fieldList.push({type:'BigDecimal',value:'auxiliaryQuantity',text:'辅助数量',dictCode:''})
        fieldList.push({type:'string',value:'qualityInspectionStatus',text:'质检状态',dictCode:'zj_status'})
        fieldList.push({type:'string',value:'remarks',text:'主表备注',dictCode:''})
        fieldList.push({type:'string',value:'subtableRemarks',text:'子表备注',dictCode:''})
        fieldList.push({type:'string',value:'status',text:'状态',dictCode:'kc_status'})
        fieldList.push({type:'string',value:'preparedBy',text:'制单人',dictCode:''})
        fieldList.push({type:'date',value:'preparedTime',text:'制单日期'})
        fieldList.push({type:'string',value:'supplierId',text:'供应商',dictCode:"erp_supplier,name,id"})
        fieldList.push({type:'string',value:'supplierCode',text:'供应商编号',dictCode:''})
        fieldList.push({type:'string',value:'supplierName',text:'供应商名称',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>